package com.umeox.ota.engine;

import android.util.Pair;

import com.umeox.ota.data.constant.Constant;
import com.umeox.ota.data.local.CustomConfig;
import com.umeox.ota.utils.DeviceUtil;
import com.abupdate.fotainject.FotaInjector;
import com.abupdate.iot_libs.OtaAgentPolicy;
import com.abupdate.iot_libs.engine.policy.PolicyManager;
import com.abupdate.iot_libs.interact.callback.IParsePolicyListener;
import com.abupdate.iot_libs.utils.SPFTool;
import com.abupdate.sdk_annotation.Inject;
import com.abupdate.trace.Trace;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author fighter_lee
 * @date 2018/2/2
 * <p>
 * 自定义强制升级策略
 */
public class PolicyInstallForce implements IParsePolicyListener {
    public static final String TAG = PolicyInstallForce.class.getSimpleName();

    @Inject
    PolicyManager policyManager;

    @Override
    public boolean doParse() {
        FotaInjector.inject(this);
        //获取强制升级时间区间
        Pair<Date, Date> forceInstallTime = policyManager.getForceInstallTime();
        //判断当前时间是否处于强制升级的时间内
        if (inForceInstallTime(forceInstallTime) || SPFTool.getBoolean(Constant.SP_OTA_SILENT_UPDATE, false)) {
            //判断是否需要判断息屏条件
            Trace.d(TAG, "doParse() current time is in force install time");
            if (CustomConfig.getInstance().screenJudge) {
                boolean screenOn = DeviceUtil.isScreenOn(OtaAgentPolicy.sCx);
                Trace.d(TAG, "doParse() force install feature will need judge screen, screen is: %s", (screenOn ? "on" : "off"));
                return !screenOn;
            }
            return true;
        }
        Trace.d(TAG, "doParse() current time isn't in force install time");
        return false;
    }

    private boolean inForceInstallTime(Pair<Date, Date> forceInstallTime) {
        if (null == forceInstallTime) {
            return false;
        }
        Date from = forceInstallTime.first;
        Date to = forceInstallTime.second;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String nowTime = sdf.format(new Date());
        try {
            Date current = sdf.parse(nowTime);
            Date twentyFour = sdf.parse("24:00");
            Date zero = sdf.parse("00:00");
            if (from.after(to)) {
                //起始时间 > 结束时间 -> 隔夜
                if ((current.after(from) && current.before(twentyFour)) ||
                        (current.after(zero) && current.before(to))) {
                    return true;
                } else {
                    return false;
                }
            } else {
                if (current.after(from) && current.before(to)) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }
}
